﻿using System.Linq;

// ReSharper disable once CheckNamespace
// 限定名称空间以减少引用
namespace System
{
    public static class ExceptionExtension
    {
        /// <summary>
        /// 从聚合的异常中提取指定异常，并约定包含多个异常或者不包含异常的时候视为错误
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="aggException"></param>
        /// <returns></returns>
        public static T Assert<T>(this AggregateException aggException)
            where T : Exception
        {
            var ex = aggException.InnerExceptions
                .OfType<T>()
                .ToList();
            if (!ex.Any() || ex.Count > 1)
                throw aggException;
            return ex.First();
        }
    }
}
